package com.best.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.best.dto.FoodWithComment;
import com.best.mapper.CommentMapper;
import com.best.mapper.FoodMapper;
import com.best.mapper.LoveFoodMapper;
import com.best.pojo.Food;
import com.best.pojo.FoodComment;
import com.best.pojo.LoveFood;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @author yangruyi
 * @date 2021/3/11
 */
@Service
public class FoodService {

    private final static String UPLOAD_FOLDER = "C:\\best-menu\\";

    @Autowired
    private FoodMapper foodMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private LoveFoodMapper loveFoodMapper;

    public boolean addFood(Food food) {
        food.setId(null);
        return foodMapper.insert(food) >= 1;
    }

    public boolean del(String id) {
        return foodMapper.deleteById(id) >= 1;
    }

    public boolean edit(Food food) {
        return foodMapper.updateById(food) >= 1;
    }

    public List<Food> all(String name, Integer series, Integer snack, Integer taste, Integer effect,String userId) {
        QueryWrapper<Food> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<Food> lambda = wrapper.lambda().eq(Food::getState, 1).orderByDesc(Food::getThumb);
        if (Objects.nonNull(name)) {
            lambda.like(Food::getFoodName, name);
        }
        if (Objects.nonNull(series)) {
            lambda.eq(Food::getSeries, series);
        }
        if (Objects.nonNull(snack)) {
            lambda.eq(Food::getSnack, snack);
        }
        if (Objects.nonNull(taste)) {
            lambda.eq(Food::getTaste, taste);
        }
        if (Objects.nonNull(effect)) {
            lambda.eq(Food::getEffect, effect);
        }
        if(Objects.nonNull(userId)){
            lambda.eq(Food::getUserId,userId);
        }
        return foodMapper.selectList(wrapper);
    }
    public FoodWithComment foodDetail(String foodId){
        FoodWithComment withComment = new FoodWithComment();
        QueryWrapper<FoodComment> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(FoodComment::getFoodId,foodId);
        List<FoodComment> foodComments = commentMapper.selectList(wrapper);
        withComment.setComments(foodComments);
        Food food = foodMapper.selectById(foodId);
        withComment.setFood(food);
        return withComment;
    }
    public boolean love(String id) {
        Food food = foodMapper.selectById(id);
        food.setThumb(food.getThumb() + 1);
        return foodMapper.updateById(food) >= 1;
    }

    public List<FoodComment> comments(String id) {
        QueryWrapper<FoodComment> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(FoodComment::getFoodId, id);
        return commentMapper.selectList(wrapper);
    }

    public boolean addComment(FoodComment comment) {
        comment.setCreateTime(new Date());
        return commentMapper.insert(comment) >= 1;
    }

    /**
     * 收藏
     *
     * @param foodId
     * @param userId
     * @return
     */
    public boolean addCollect(String foodId, String userId) {
        LoveFood loveFood = new LoveFood();
        loveFood.setFoodId(foodId);
        loveFood.setUserId(userId);
        return loveFoodMapper.insert(loveFood) >= 1;
    }

    public boolean subCollect(String foodId, String userId) {
        QueryWrapper<LoveFood> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(LoveFood::getFoodId, foodId).eq(LoveFood::getUserId, userId);
        return loveFoodMapper.delete(wrapper) >= 1;
    }
    public String uploadImage(MultipartFile file){
        Path path = null;
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newName = UUID.randomUUID().toString().replace("-","") + suffix;
        try {
            byte[] bytes = file.getBytes();
            Path dir = Paths.get(UPLOAD_FOLDER);
            path = Paths.get(UPLOAD_FOLDER + newName);
            if (!Files.exists(path)) {
                Files.createDirectories(dir);
            }
            Files.write(path, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newName;
    }
    public void getImage(String filename, HttpServletResponse response){
        FileInputStream in = null;
        ServletOutputStream out = null;
        try {
            File file = new File(UPLOAD_FOLDER+filename);
            in = new FileInputStream(file);
            out = response.getOutputStream();
            byte[] bytes = new byte[1024 * 10];
            int len = 0;
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes,0,len);
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
